<?php

declare(strict_types=1);

namespace App\AdminApi\Modular\System\Controller;

use App\AdminApi\BasicsController;
use App\Common\Extend\Guard\Auth;
use App\Common\Modular\System\Serve\ConfigureServe;
use Core\HyperfUnit\Response;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\{Controller, GetMapping, PostMapping};
use Psr\Http\Message\ResponseInterface;
use Zms\Exception\AppException;
use Zms\Unit\Arr;

#[
    Auth(guard: self::GUARD, label: ['系统管理'], app: self::APP),
    Controller(prefix: "/admin-api/system-configure", server: self::SERVER)
]
class ConfigureController extends BasicsController
{

    #[Inject]
    protected ConfigureServe $service;

    #[
        GetMapping('data'),
        Auth(label: ['查看'], sign: 'system.configure', describe: "查看系统配置", view: '/system/configure/index')
    ]
    public function data(): ResponseInterface
    {
        $key = $this->request->input('key');
        try {
            $form = $this->service->getForm($key, "/admin-api/system-configure/save?key={$key}");
            return Response::Api()->success(data: $form);
        } catch (AppException $exception) {
            return Response::Api()->fail($exception->getMessage());
        }
    }


    #[
        PostMapping('save'),
        Auth(label: ['修改'], sign: "system.configure.updated", describe: "修改系统配置")
    ]
    public function save(): ResponseInterface
    {
        $key = $this->request->input('key');
        $data = $this->request->post();
        if (gettype($data) === 'array' && Arr::type($data) === 'map') {
            if ($this->service->writeConfiguration($key, $data)) {
                cache()->clear();
                return Response::Api()->success('配置保存成功,如未生效请清理系统缓存');
            }
            return Response::Api()->fail('配置保存失败');
        }
        return Response::Api()->fail('数据错误,请刷新重试');
    }


    #[
        GetMapping('classify'),
        Auth(label: ['配置分类'], relyon: ["system.configure"], logger: false)
    ]
    public function classify(): ResponseInterface
    {
        return Response::Api()->success(data: $this->service->getClassify());
    }
}